const Router = require('koa-router');
const router = new Router();
router.prefix('/substation'); //路由前缀
const Joi = require('joi'); //前端参数验证
const Jwt = require('jsonwebtoken'); //token生成器
const Moment = require('moment'); //时间格式化
const Mongoose = require('mongoose'); //导入mongoose
const token = require('../utility/token'); //token公共方法
const common = require('../utility/common'); //程序公共方法
const verifyWeb = require("../config/verifyWeb"); //验证前端参数
//模型
const SubsModel = require("../models/subs"); //变电站
//数据库字段
const dbDoc = require("../config/dbDoc");

//查询
router.post('/search', async (ctx, next) => {
    //定义返回值
    var cb = {
        list: [],
        count: 0
    };
    try {
        //根据用户权限获取sid取值范围
        let sidRegion = await common.region(ctx, 9);
        if (!sidRegion) {
            return ctx.body = cb;
        };
        //前端参数【req：获取前端所有参数，search：查询条件，sorType：排序条件，page：当前页码，pageSize：每页显示条数】
        let req = ctx.request.body,
            search = {},
            sorType = {},
            page = 1,
            pageSize = 20;
        //处理前端数据
        for (let i in req) {
            if (i == "search") {
                for (let j in req[i]) {
                    if (req[i][j].length) {
                        search[j] = req[i][j];
                    }
                }
            };
            if (i == 'sorType') {
                for (let j in req[i]) {
                    if (req[i][j]) {
                        sorType = req[i][j];
                    }
                }
            };
            if (i == 'page') {
                page = Number(req[i]);
            };
            if (i == 'pageSize') {
                pageSize = Number(req[i]);
            };
        };
        console.log('sidRegion', sidRegion)
        //定义查询参数【match：默认使用sid进行查询，group：统计条件，sort：排序条件，skip：跳过多少数据，limit：展示多少条数据】
        var match = {
            "sid": sidRegion
        };
        let group = {};
        let sort = {};
        let skip = (page - 1) * pageSize;
        let limit = pageSize;
        /**
         * 查询条件判定
         * filterStr：字符串类型筛选【short：变电站简称，type：变电站类型，owner：产权单位，maintainer：运维单位】
         * filterStr：数值类型筛选【status：变电站状态，voltage：电压等级，grade：调度等级】
         * filterStr：时间类型筛选【crtime：开始时间】
         */
        let filterStr = ['short', 'type', 'owner', 'maintainer'];
        let filterNum = ['status', 'voltage', 'grade'];
        let filterDate = ['crtime'];
        for (let i in search) {
            filterStr.forEach(str => {
                if (i == str) {
                    let arr = [];
                    let searchArr = search[i];
                    searchArr.forEach(item => {
                        if (item == 'null') {
                            arr.push(String(item));
                        } else {
                            arr.push(String(item));
                        }
                    });
                    match[i] = {
                        "$in": arr
                    };
                };
            });
            filterNum.forEach(num => {
                if (i == num) {
                    let arr = [];
                    let searchArr = search[i];
                    searchArr.forEach(item => {
                        if (item == 'null') {
                            arr.push(String(item));
                        } else {
                            arr.push(Number(item));
                        }
                    });
                    match[i] = {
                        "$in": arr
                    };
                }
            });
            filterDate.forEach(time => {
                if (i == time) {
                    let timeArr = search[i];
                    let obj = {};
                    if (timeArr[0] == timeArr[1] || timeArr[1] == undefined) {
                        let end = new Date(timeArr[0]);
                        end.setDate(new Date(timeArr[0]).getDate() + 1);
                        end.setHours(0);
                        end.setMinutes(0);
                        end.setSeconds(0);
                        end.setMilliseconds(0);
                        obj.$gte = Number(Date.parse(timeArr[0]) / 1000);
                        obj.$lt = Number(Date.parse(end) / 1000);
                    } else {
                        obj.$gte = Number(Date.parse(timeArr[0]) / 1000);
                        obj.$lt = Number(Date.parse(timeArr[1]) / 1000 + 85399); //结束时间需要加86400【一天】
                    };
                    match[i] = obj;
                }
            });
        };
        //排序条件
        if (sorType) {
            let defaultSort = {
                _id: -1
            };
            sort = Object.assign(sorType, defaultSort); //合并两个对象
        } else {
            sort = {
                _id: -1
            };
        };
        //查询【listParam：定义的查询参数，subs：查询的结果】
        let listParam = [{
                '$match': match
            },
            {
                '$sort': sort
            },
            {
                '$skip': skip
            },
            {
                '$limit': limit
            },
        ];
        let list = await SubsModel.aggregate(listParam);
        //构造返回值
        if (list.length) {
            list.map(obj => {
                obj.crtime = Moment(obj.crtime).format('YYYY-MM-DD HH:mm:ss');
                obj.chtime = Moment(obj.chtime).format('YYYY-MM-DD HH:mm:ss');
                return obj;
            });
            cb.list = list;
        };
    } catch (e) {
        cb = {
            list: [],
            count: 0
        };
    } finally {
        ctx.body = cb;
    };
});

//统计
router.post('/statis', async (ctx, next) => {
    //定义返回值
    let cb = {
        gradeGroup: [],
        mainGroup: [],
        ownerGroup: [],
        shortGroup: [],
        statusGroup: [],
        typeGroup: [],
        voltageGroup: []
    };
    try {
        //前端参数
        let req = ctx.request.body;
        //获取用户权限
        let userRegion = await common.userRegion(ctx);
        //根据用户权限查询用户列表
        let userList = await UserModel.find({
            region: {
                $regex: userRegion
            }
        });
        cb = userList;
    } catch (e) {
        cb = [];
    } finally {
        ctx.body = cb;
    };
});

//用户新增
router.post('/userAdd', async (ctx, next) => {
    //定义返回值
    let cb = {
        sta: false,
        msg: '新增用户失败'
    };
    try {
        //前端参数
        let req = ctx.request.body;
        //前端参数验证
        let valityWeb = await Joi.validate({
            name: req.name,
            password: req.password,
            region: req.region
        }, verifyWeb.userAdd);
        //验证用户名是否存在
        let verifyName = await UserModel.findOne({
            name: String(req.name)
        });
        if (verifyName) {
            cb.msg = '用户名已存在';
            return ctx.body = cb;
        };
        //存储用户
        let user = new UserModel({
            _id: mongoose.Types.ObjectId(),
            name: req.name,
            password: req.password,
            crtime: moment().format('X'),
            chtime: moment().format('X'),
            region: req.region
        });
        let save = await user.save();
        //构造返回值
        cb = {
            sta: true,
            msg: '新增用户成功',
            cb: save
        };
    } catch (e) {
        cb = {
            sta: false,
            msg: '新增用户失败'
        };
    } finally {
        ctx.body = cb;
    };
});

//用户详情
router.post('/userDetail', async (ctx, next) => {
    //定义返回值
    let cb = {
        list: {},
        sta: false,
        msg: '获取用户详情失败'
    };
    try {
        //前端参数
        let req = ctx.request.body;
        //前端参数验证
        let valityWeb = await Joi.validate({
            _id: req._id
        }, verifyWeb._id);
        //查询用户
        let user = await UserModel.findById(mongoose.Types.ObjectId(req._id), dbDoc.user).lean();
        if (user) {
            for (let i in user) {
                if (i == 'crtime' || i == 'chtime') {
                    user[i] = moment(Date.now(user[i])).format('YYYY-MM-DD HH:mm:ss');
                } else {
                    user[i] = user[i];
                };
            };
        };
        //构造返回值
        cb.list = user;
        cb.sta = true;
        cb.msg = '获取用户详情成功';
    } catch (e) {
        cb = {
            list: {},
            sta: false,
            msg: '获取用户详情失败'
        };
    } finally {
        ctx.body = cb;
    };
});

//用户编辑
router.post('/userEdit', async (ctx, next) => {
    //定义返回值
    let cb = {
        sta: false,
        msg: '编辑用户失败'
    };
    try {
        //前端参数
        let req = ctx.request.body;
        console.log('req', req);
        //前端参数验证
        let valityWeb = await Joi.validate({
            _id: req._id,
            name: req.name,
            password: req.password,
            region: req.region
        }, verifyWeb.userEdit);
        console.log('valityWeb', valityWeb);
        if (!valityWeb) {
            cb.msg = '参数错误';
            return ctx.body = cb;
        };
        //验证是否存在
        let verifyExist = await UserModel.findById(mongoose.Types.ObjectId(req._id), dbDoc.user).lean();
        console.log('verifyExist', verifyExist);
        if (!verifyExist) {
            cb.msg = '用户不存在';
            return ctx.body = cb;
        };
        //更新
        let doc = {};
        for (let i in req) {
            if (i != '_id') {
                doc[i] = req[i];
            };
            doc.chtime = moment().format('X');
        };
        let updateOne = await UserModel.findOneAndUpdate(req._id, doc, {
            new: true
        });
        console.log('updateOne', updateOne);
        //构造返回值
        if (updateOne) {
            cb = {
                sta: true,
                msg: '编辑用户成功',
                cb: updateOne
            };
        };
    } catch (e) {
        cb = {
            sta: false,
            msg: '编辑用户失败'
        };
    } finally {
        ctx.body = cb;
    };
});


module.exports = router;